﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using AnalisisDeRiesgos.Dal;

namespace AnalisisDeRiesgos.Models.Danger
{
    public class SearchDangerModel
    {
        [DisplayName("Jefatura/Gerencia")]
        [Required(ErrorMessage = "La Jefatura/Gerencia es requerida")]
        public int Management { get; set; }

        [DisplayName("Proceso")]
        [Required(ErrorMessage = "El Proceso es requerido")]
        public int Process { get; set; }

        [DisplayName("Area")]
        [Required(ErrorMessage = "El Area es requerido")]
        public int Area { get; set; }

        [DisplayName("Actividad")]
        [Required(ErrorMessage = "La Actividad es requerida")]
        public int Activity { get; set; }

        #region DropdownLists
        public IEnumerable<SelectListItem> Managements
        {
            get
            {
                return managementList;
            }
        }

        public IEnumerable<SelectListItem> Processes
        {
            get
            {
                return processList;
            }
        }

        public IEnumerable<SelectListItem> Areas
        {
            get
            {
                return areaList;
            }
        }

        public IEnumerable<SelectListItem> Activitys
        {
            get
            {
                return activityList;
            }
        }

        private List<SelectListItem> managementList;
        private List<SelectListItem> processList;
        private List<SelectListItem> areaList;
        private List<SelectListItem> activityList;
        #endregion

        riskanalysisEntities entities = new riskanalysisEntities();

        public List<SearchDangerInfo> DangerInfo
        {
            get
            {
                return dangerInfo;
            }
        }

        private List<SearchDangerInfo> dangerInfo;

        public SearchDangerModel()
        {
            Utils.GetFrequencyList();
            Utils.GetAffectedList();
            Utils.GetControlExistenceList();
            Utils.GetSeverityList();
            FillList();
            SearchDanger();
        }

        private void FillList()
        {
            managementList = new List<SelectListItem>();

            var queryManagements = from m in entities.managements
                                   where m.enabled
                                   select m;

            foreach (management item in queryManagements)
            {
                managementList.Add(
                    new SelectListItem
                    {
                        Text = item.name,
                        Value = item.managementId.ToString()
                    });
            }

            managementList.Add(new SelectListItem { Text = "Todos", Value = "0", Selected = true });
            processList = Utils.FillProcessList(Management);
            processList.Add(new SelectListItem { Text = "Todos", Value = "0", Selected = true });
            areaList = Utils.FillAreaList(Process);
            areaList.Add(new SelectListItem { Text = "Todos", Value = "0", Selected = true });
            activityList = Utils.FillActivityList(Area);
            activityList.Add(new SelectListItem { Text = "Todos", Value = "0", Selected = true });
        }

        public void SearchDanger()
        {
            IQueryable<danger> query = from d in entities.dangers
                                 select d;
            if (Management != 0)
            {
                query = from d in entities.dangers
                        where d.activity.area.process.management.managementId == Management
                        select d;

                if (Process != 0)
                {
                    query = from d in entities.dangers
                            where d.activity.area.process.management.managementId == Management &&
                                   d.activity.area.process.processId == Process
                            select d;
                    if (Area != 0)
                    {
                        query = from d in entities.dangers
                                where d.activity.area.process.management.managementId == Management &&
                                       d.activity.area.process.processId == Process &&
                                       d.activity.area.areaId == Area
                                select d;

                        if (Activity != 0)
                            query = from d in entities.dangers
                                    where d.activity.area.process.management.managementId == Management &&
                                           d.activity.area.process.processId == Process &&
                                           d.activity.area.areaId == Area &&
                                           d.activity.activityId == Activity
                                    select d;
                    }
                }
            }
            List<danger> theList = new List<danger>();

            foreach (danger item in query)
            {
                theList.Add(item);
            }

            Utils.GetKValuesList();
            dangerInfo = new List<SearchDangerInfo>();

            foreach (danger d in theList)
            {             
                var theDanger = new
                {
                    DangerId = d.dangerId,
                    Management = d.activity.area.process.management.name,
                    Process = d.activity.area.process.name,
                    Area = d.activity.area.name,
                    Activity = d.activity.name,
                    Causes = d.causes,
                    Consecuences = d.consecuences,
                    Controls = d.controlExistence,
                    Danger = d.description,
                    EspecificUbication = d.ubication,
                    ExistingControls = d.controls,
                    ExpirationDate = d.expirationDate,
                    ExposedNumber = d.exposed,
                    Frequence = d.frecuence,
                    KFactor = d.kFactor,
                    OperativeCondition = d.operativeCondition,
                    PosibleControls = d.posibleControls,
                    Risk = d.risk.name,
                    Severity = d.severity,
                    Status = d.status,
                    AffectedTarget = d.affectedTarget,
                    Inversion = d.inversion
                };
                SearchDangerInfo info = new SearchDangerInfo
                {
                    DangerId = theDanger.DangerId,
                    Management = theDanger.Management,
                    Process = theDanger.Process,
                    Area = theDanger.Area,
                    Activity = theDanger.Activity,
                    Causes = theDanger.Causes.Replace("\n", "<br />"),
                    Consecuences = theDanger.Consecuences.Replace("\n", "<br />"),
                    Controls = Utils.ControlExistance[theDanger.Controls - 1],
                    Danger = theDanger.Danger.Replace("\n", "<br />"),
                    EspecificUbication = theDanger.EspecificUbication.Replace("\n", "<br />"),
                    ExistingControls = theDanger.ExistingControls.Replace("\n", "<br />"),
                    ExpirationDate = theDanger.ExpirationDate.ToString("d", Utils.culture),
                    ExposedNumber = Utils.Affecteds[theDanger.ExposedNumber - 1],
                    Frequence = Utils.Frequences[theDanger.Frequence - 1],
                    KFactor = Utils.KValuesDictionary[theDanger.KFactor],
                    OperativeCondition = theDanger.OperativeCondition.Equals("N") ? "Normal" : "Anormal",
                    AffectedTarget = theDanger.AffectedTarget.Equals("H") ? "Humano" : "Infraestructura",
                    PosibleControls = theDanger.PosibleControls.Replace("\n", "<br />"),
                    Risk = theDanger.Risk,
                    Severity = Utils.Severitys[theDanger.Severity - 1],
                    Status = theDanger.Status.ToString(),
                    Inversion = theDanger.Inversion.ToString()
                };
                info.CalculateRisk(d);
                dangerInfo.Add(info);
            }
        }
    }
}